<?php
/**
 * 会员模型
 *
 *
 *
 * * @网店运维 (c) 2015-2018 ShopWWI Inc. (http://www.shopwwi.com)
 * @license    http://www.shopwwi.c om
 * @link       交流群号：111731672
 * @since      网店运维提供技术支持 授权请购买shopnc授权
 */
defined('ByShopWWI') or exit('Access Invalid!');
class memberModel extends Model {
    
    private static $downline_member_fee=0;//某会员的所有下线会员费总和
    private static $downline_members=array();//某会员的所有下线会员ID
    
 
    private static $upline_member_and_fee=array();//某会员的所有上线会员（ID-业绩）array('member_id'=>0,'fee'=>0)
            
    public function __construct(){
        parent::__construct('member');
    }

    /**
     * 会员详细信息（查库）
     * @param array $condition
     * @param string $field
     * @return array
     */
    public function getMemberInfo($condition, $field = '*', $master = false) {
        return $this->table('member')->field($field)->where($condition)->master($master)->find();
    }

    /**
     * 取得会员详细信息（优先查询缓存）
     * 如果未找到，则缓存所有字段
     * @param int $member_id
     * @param string $field 需要取得的缓存键值, 例如：'*','member_name,member_sex'
     * @return array
     */
    public function getMemberInfoByID($member_id, $fields = '*') {

        $member_info = rcache($member_id, 'member', $fields);
        if (empty($member_info)) {
            $member_info = $this->getMemberInfo(array('member_id'=>$member_id),'*',true);
            wcache($member_id, $member_info, 'member');
        }
        return $member_info;
    }

    /**
     * 会员列表
     * @param array $condition
     * @param string $field
     * @param number $page
     * @param string $order
     */
    public function getMemberList($condition = array(), $field = '*', $page = null, $order = 'member_id desc', $limit = '') {
       return $this->table('member')->field($field)->where($condition)->page($page)->order($order)->limit($limit)->select();
    }

    /**
    *获取佣金订单数量
    *
    */
    public function getOrderInviteCount($inviteid,$memberid)
    {
        return $this->table('pd_log')->where(array('lg_invite_member_id' => $memberid,'lg_member_id' => $inviteid))->count();
    }
    /**
    *获取佣金订单总金额
    *
    */
     public function getOrderInviteamount($inviteid,$memberid)
    {
	return $this->table('pd_log')->where(array('lg_invite_member_id' => $memberid,'lg_member_id' => $inviteid))->sum('lg_av_amount');
    }
    /**
     * 会员列表
     * @param array $condition
     * @param string $field
     * @param number $page
     * @param string $order
     */
    public function getMembersList($condition, $page = null, $order = 'member_id desc', $field = '*') {
       return $this->table('member')->field($field)->where($condition)->page($page)->order($order)->select();
    }


    /**
     * 删除会员
     *
     * @param int $id 记录ID
     * @return array $rs_row 返回数组形式的查询结果
     */
    public function del($id){
            if (intval($id) > 0){
                    $where = " member_id = '". intval($id) ."'";
                    $result = Db::delete('member',$where);
                    return $result;
            }else {
                    return false;
            }
    }

    /**
     * 会员数量
     * @param array $condition
     * @return int
     */
    public function getMemberCount($condition) {
        return $this->table('member')->where($condition)->count();
    }

    /**
     * 编辑会员
     * @param array $condition
     * @param array $data
     */
    public function editMember($condition, $data) {
       
        $update = $this->table('member')->where($condition)->update($data);
        if ($update && $condition['member_id']) {
            dcache($condition['member_id'], 'member');
        }
        return $update;
    }

    /**
     * 登录时创建会话SESSION
     *http://s.shopwwi.com/data/upload/mobile/special/s0/s0_05093194479621777.jpghttp://s.shopwwi.com/wap/tmpl/product_list.html?keyword=%E8%8F%9C
     * @param array $member_info 会员信息
     */
    public function createSession($member_info = array(),$reg = false) {
        if (empty($member_info) || !is_array($member_info)) return ;

        $_SESSION['is_login']   = '1';
        $_SESSION['member_id']  = $member_info['member_id'];
        $_SESSION['member_name']= $member_info['member_name'];
        $_SESSION['member_email']= $member_info['member_email'];
        $_SESSION['is_buy']     = isset($member_info['is_buy']) ? $member_info['is_buy'] : 1;
        $_SESSION['avatar']     = $member_info['member_avatar'];
        
        // 头衔COOKIE
        $this->set_avatar_cookie();

        $seller_info = Model('seller')->getSellerInfo(array('member_id'=>$_SESSION['member_id']));
        $_SESSION['store_id'] = $seller_info['store_id'];

        if (trim($member_info['member_qqopenid'])){
            $_SESSION['openid']     = $member_info['member_qqopenid'];
        }
        if (trim($member_info['member_sinaopenid'])){
            $_SESSION['slast_key']['uid'] = $member_info['member_sinaopenid'];
        }

        if (!$reg) {
            //添加会员积分
            $this->addPoint($member_info);
            //添加会员经验值
            $this->addExppoint($member_info);
        }

        if(!empty($member_info['member_login_time'])) {
            $update_info    = array(
                'member_login_num'=> ($member_info['member_login_num']+1),
                'member_login_time'=> TIMESTAMP,
                'member_old_login_time'=> $member_info['member_login_time'],
                'member_login_ip'=> getIp(),
                'member_old_login_ip'=> $member_info['member_login_ip']
            );
            $this->editMember(array('member_id'=>$member_info['member_id']),$update_info);
        }
        setNcCookie('cart_goods_num','',-3600);
        // cookie中的cart存入数据库
        Model('cart')->mergecart($member_info,$_SESSION['store_id']);
        // cookie中的浏览记录存入数据库
        Model('goods_browse')->mergebrowse($_SESSION['member_id'],$_SESSION['store_id']);
        
        // 自动登录
        if ($member_info['auto_login'] == 1) {
            $this->auto_login();
        }
    }
	
    /**
     * 获取会员信息
     *
     * @param	array $param 会员条件
     * @param	string $field 显示字段
     * @return	array 数组格式的返回结果
     */
    public function infoMember($param, $field='*') {
        if (empty($param)) return false;

            //得到条件语句
            $condition_str	= $this->getCondition($param);
            $param	= array();
            $param['table']	= 'member';
            $param['where']	= $condition_str;
            $param['field']	= $field;
            $param['limit'] = 1;
            $member_list	= Db::select($param);
            $member_info	= $member_list[0];
            if (intval($member_info['store_id']) > 0){
                  $param	= array();
                  $param['table']	= 'store';
                  $param['field']	= 'store_id';
                  $param['value']	= $member_info['store_id'];
                  $field	= 'store_id,store_name,grade_id';
                  $store_info	= Db::getRow($param,$field);
                  if (!empty($store_info) && is_array($store_info)){
                          $member_info['store_name']	= $store_info['store_name'];
                          $member_info['grade_id']	= $store_info['grade_id'];
                  }
            }
            return $member_info;
    }
    
    /**
     * 7天内自动登录
     */
    public function auto_login() {
        // 自动登录标记 保存7天
        setNcCookie('auto_login', encrypt($_SESSION['member_id'], MD5_KEY), 7*24*60*60);
    }
    
    public function set_avatar_cookie() {
        setNcCookie('member_avatar', $_SESSION['avatar'], 365*24*60*60);
    }

    /**
     * 注册
     */
    public function register($register_info) {
        // 注册验证
        $obj_validate = new Validate();
        $obj_validate->validateparam = array(
        array(
                "input"=>$register_info["username"],
                "require"=>"true",
                "message"=>'用户名不能为空'
            ),
        array(
                "input" => $register_info["username"],
                "validator" => "username",
                "message" => "请填写字母、数字、中文、_"
            ),
        array(
               "input"=>$register_info["password"],
                "require"=>"true",
                "message"=>'密码不能为空'
            ),
        array(
                "input"=>$register_info["password_confirm"],
                "require"=>"true",
                "validator"=>"Compare",
                "operator"=>"==",
                "to"=>$register_info["password"],
                "message"=>'密码与确认密码不相同'
            ),
        array(
                "input"=>$register_info["password_confirm"],
                "require"=>"true",
                "validator"=>"Compare",
                "operator"=>"==",
                "to"=>$register_info["password"],
                "message"=>'密码与确认密码不相同'
            ),
        array(
               "input"=>$register_info["mobile"],
                "require"=>"true",
                "message"=>'手机号不能为空'
            ),
         array(
               "input"=>$register_info["inviter_id"],
                "require"=>"true",
                "message"=>'推荐人不能为空'
            ),
        array(
               "input"=>$register_info["node_id"],
                "require"=>"true",
                "message"=>'节点人不能为空'
            ),
       
        );
       
        $error = $obj_validate->validate();
        if ($error != ''){
            return array('error' => $error);
        }

        // 验证用户名是否重复
        $check_member_name  = $this->getMemberInfo(array('member_name'=>$register_info['username']));
        if(is_array($check_member_name) and count($check_member_name) > 0) {
            return array('error' => '用户名已存在');
        }
	// 验证手机号是否重复
        $check_member_mobile  = $this->getMemberInfo(array('member_mobile'=>$register_info['mobile']));
        if(is_array($check_member_mobile) and count($check_member_mobile) > 0) {
            return array('error' => '手机号码已存在');
        }
       

       
        // 会员添加
        $member_info = array();
        $member_info['member_name']         = $register_info['username'];
        $member_info['member_type']         = $register_info['member_type'];
        $member_info['member_truename']     = $register_info['member_truename'];
        $member_info['member_passwd']       = $register_info['password'];
        $member_info['member_mobile']       = $register_info['mobile'];
        $member_info['member_email']        = $register_info['email'];
        $member_info['identification_card'] = $register_info['identification_card'];
        
        $member_info['inviter_id']          = $register_info['inviter_id'];
        $member_info['invite_one']          = $register_info['invite_one'];
        $member_info['invite_two']          = $register_info['invite_two'];
        $member_info['invite_three']        = $register_info['invite_three'];
        $member_info['node_id']             = $register_info['node_id'];
        $member_info['node_one']            = $register_info['node_one'];
        $member_info['node_two']            = $register_info['node_two'];
        $member_info['node_three']          = $register_info['node_three'];
        
      
        $member_fee=$this->getConsumeAmountByMemberType($register_info['member_type']);
        
        // 验证报单中心账户的报单币是否充足
        $check_member_coin  = $this->getMemberInfo(array('member_id'=>$_SESSION['member_id']));
        if(is_array($check_member_coin) and count($check_member_coin) > 0) {
            if($check_member_coin['submit_coin']<$member_fee)
            {
                return array('error' => '您的报单币不足，请充值');
            }
            
        }
        else
        {
            return array('error' => '您的账户不存在');
        }
        
        
        
        
       
        $insert_id  = $this->addMember($member_info);
        if($insert_id) {
            
            $member_info['member_id'] = $insert_id;
            $member_info['is_buy'] = 1;
         
            
            //扣除报单人的报单币
            $model_coin=Model('coin');
            $model_coin->writeLog($_SESSION['member_id'],-$member_fee,'register',$member_info['member_id'],$member_info['member_name'],$member_info['member_type']);
             
            
            //发放报单中心人的报单补助金
            $help_amount=$member_fee*SUBMIT_PERCENT;
            $this->writeLog($_SESSION['member_id'],$help_amount,'submit_form',$member_info['member_id'],$member_info['member_name'],$member_info['member_type']);
            return $member_info;
        } 
        else {
            return array('error' => '注册失败');
        }

    }

    /**
     * 注册商城会员
     *
     * @param   array $param 会员信息
     * @return  array 数组格式的返回结果
     */
    public function addMember($param) {
       
        if(empty($param)) {
            return false;
        }
        try {
            $this->beginTransaction();
            $member_info    = array();
            $member_info['member_id']           = $param['member_id'];
            $member_info['member_name']         = $param['member_name'];
            $member_info['member_type']         = $param['member_type'];
            $member_info['member_passwd']       = md5(trim($param['member_passwd']));
            $member_info['member_email']        = $param['member_email'];
            $member_info['member_time']         = TIMESTAMP;
            $member_info['member_login_time']   = TIMESTAMP;
            $member_info['member_old_login_time']= TIMESTAMP;
            $member_info['member_login_ip']     = getIp();
            $member_info['member_old_login_ip'] = $member_info['member_login_ip'];

            $member_info['member_truename']     = $param['member_truename'];
            $member_info['member_qq']           = $param['member_qq'];
            $member_info['member_sex']          = $param['member_sex'];
            $member_info['member_avatar']       = $param['member_avatar'];
            $member_info['member_qqopenid']     = $param['member_qqopenid'];
            $member_info['member_qqinfo']       = $param['member_qqinfo'];
            $member_info['member_sinaopenid']   = $param['member_sinaopenid'];
            $member_info['member_sinainfo']     = $param['member_sinainfo'];
            
            
            $member_info['identification_card'] = $param['identification_card'];
           
            $member_info['inviter_id']          = $param['inviter_id'];
            $member_info['invite_one']          = $param['invite_one'];
            $member_info['invite_two']          = $param['invite_two'];
            $member_info['invite_three']        = $param['invite_three'];
            $member_info['node_id']             = $param['node_id'];
            $member_info['node_one']            = $param['node_one'];
            $member_info['node_two']            = $param['node_two'];
            $member_info['node_three']          = $param['node_three'];
            
            $member_fee=$this->getConsumeAmountByMemberType($param['member_type']);//新注册会员的会员费
            $member_info['member_fee']          = $member_fee;
			
            if(preg_match('/^0?(13|15|17|18|14)[0-9]{9}$/i', $param['member_mobile'])){
                $param['member_mobile_bind']=1;
            }
            if ($param['member_mobile_bind']) {
                $member_info['member_mobile'] = $param['member_mobile'];
                $member_info['member_mobile_bind'] = $param['member_mobile_bind'];
            }
            if ($param['weixin_unionid']) {
                $member_info['weixin_unionid'] = $param['weixin_unionid'];
                $member_info['weixin_info'] = $param['weixin_info'];
            }
           
            
            $insert_id  = $this->table('member')->insert($member_info);
            
            if (!$insert_id) {
                throw new Exception();
            }
            
            $insert = $this->addMemberCommon(array('member_id'=>$insert_id));
            if (!$insert) {
                throw new Exception();
            }
            
           
            
            
            

            // 添加默认相册
            $insert = array();
            $insert['ac_name']      = '买家秀';
            $insert['member_id']    = $insert_id;
            $insert['ac_des']       = '买家秀默认相册';
            $insert['ac_sort']      = 1;
            $insert['is_default']   = 1;
            $insert['upload_time']  = TIMESTAMP;
            $rs = $this->table('sns_albumclass')->insert($insert);
            //添加会员积分
            if (C('points_isuse')){
                Model('points')->savePointsLog('regist',array('pl_memberid'=>$insert_id,'pl_membername'=>$param['member_name']),false);
            }
          
             
          
            
            //记录消费日志
            QueueClient::push('addConsume', array('member_id'=>$insert_id,'member_name'=>$member_info['member_name'],
            'consume_amount'=>$member_fee,'consume_time'=>TIMESTAMP,'consume_remark'=>'注册会员，消费'.$member_fee));
            
            
          
            if(!empty($member_info['inviter_id']))
            {
                $this->shareReward($member_info['inviter_id'],$member_fee,$insert_id, $member_info['member_name'], $member_info['member_type']);
                $this->dynamicReward($member_info['inviter_id'], $member_fee, $insert_id, $member_info['member_name'], $member_info['member_type']);
            }
            if(!empty($member_info['node_id']))
            {
                $this->welfareReward($member_info['node_id'], $member_fee, $insert_id, $member_info['member_name'], $member_info['member_type']);
            }
             //每次注册新会员的时候，检测所有会员的复投钱包的余额是否符合复投条件
             $this->repeatRegister();
            
            
            $this->commit();
            return $insert_id;
        } catch (Exception $e) {
            $this->rollback();
            return false;
        }
    }
    
   
    /**
     * 会员登录检查
     *
     */
    public function checkloginMember() {
        if($_SESSION['is_login'] == '1') {
            @header("Location: index.php");
            exit();
        }
    }

    /**
     * 检查会员是否允许举报商品
     *
     */
    public function isMemberAllowInform($member_id) {
        $condition = array();
        $condition['member_id'] = $member_id;
        $member_info = $this->getMemberInfo($condition,'inform_allow');
        if(intval($member_info['inform_allow']) === 1) {
            return true;
        }
        else {
            return false;
        }
    }

    /**
     * 取单条信息
     * @param unknown $condition
     * @param string $fields
     */
    public function getMemberCommonInfo($condition = array(), $fields = '*') {
        return $this->table('member_common')->where($condition)->field($fields)->find();
    }

    /**
     * 插入扩展表信息
     * @param unknown $data
     * @return Ambigous <mixed, boolean, number, unknown, resource>
     */
    public function addMemberCommon($data) {
        return $this->table('member_common')->insert($data);
    }

    /**
     * 编辑会员扩展表
     * @param unknown $data
     * @param unknown $condition
     * @return Ambigous <mixed, boolean, number, unknown, resource>
     */
    public function editMemberCommon($data,$condition) {
        return $this->table('member_common')->where($condition)->update($data);
    }

    /**
     * 添加会员积分
     * @param unknown $member_info
     */
    public function addPoint($member_info) {
        if (!C('points_isuse') || empty($member_info)) return;

        //一天内只有第一次登录赠送积分
        if(trim(@date('Y-m-d',$member_info['member_login_time'])) == trim(date('Y-m-d'))) return;

        //加入队列
        $queue_content = array();
        $queue_content['member_id'] = $member_info['member_id'];
        $queue_content['member_name'] = $member_info['member_name'];
        QueueClient::push('addPoint',$queue_content);
    }

    /**
     * 添加会员经验值
     * @param unknown $member_info
     */
    public function addExppoint($member_info) {
        if (empty($member_info)) return;

        //一天内只有第一次登录赠送经验值
        if(trim(@date('Y-m-d',$member_info['member_login_time'])) == trim(date('Y-m-d'))) return;

        //加入队列
        $queue_content = array();
        $queue_content['member_id'] = $member_info['member_id'];
        $queue_content['member_name'] = $member_info['member_name'];
        QueueClient::push('addExppoint',$queue_content);
    }

    /**
     * 取得会员安全级别
     * @param unknown $member_info
     */
    public function getMemberSecurityLevel($member_info = array()) {
        $tmp_level = 0;
        if ($member_info['member_email_bind'] == '1') {
            $tmp_level += 1;
        }
        if ($member_info['member_mobile_bind'] == '1') {
            $tmp_level += 1;
        }
        if ($member_info['member_paypwd'] != '') {
            $tmp_level += 1;
        }
        return $tmp_level;
    }

    /**
     * 获得会员等级
     * @param bool $show_progress 是否计算其当前等级进度
     * @param int $exppoints  会员经验值
     * @param array $cur_level 会员当前等级
     */
    public function getMemberGradeArr($show_progress = false,$exppoints = 0,$cur_level = ''){
        $member_grade = C('member_grade')?unserialize(C('member_grade')):array();
        //处理会员等级进度
        if ($member_grade && $show_progress){
            $is_max = false;
            if ($cur_level === ''){
                $cur_gradearr = $this->getOneMemberGrade($exppoints, false, $member_grade);
                $cur_level = $cur_gradearr['level'];
            }
            foreach ($member_grade as $k=>$v){
                if ($cur_level == $v['level']){
                    $v['is_cur'] = true;
                }
                $member_grade[$k] = $v;
            }
        }
        return $member_grade;
    }

    /**
     * 获得某一会员等级
     * @param int $exppoints
     * @param bool $show_progress 是否计算其当前等级进度
     * @param array $member_grade 会员等级
     */
    public function getOneMemberGrade($exppoints,$show_progress = false,$member_grade = array()){
        if (!$member_grade){
            $member_grade = C('member_grade')?unserialize(C('member_grade')):array();
           
        }
        if (empty($member_grade)){//如果会员等级设置为空
            $grade_arr['level'] = -1;
            $grade_arr['level_name'] = '暂无等级';
            return $grade_arr;
        }

        $exppoints = intval($exppoints);

        $grade_arr = array();
        if ($member_grade){
            foreach ($member_grade as $k=>$v){
                if($exppoints >= $v['exppoints']){
                    $grade_arr = $v;
                }
            }
        }
        
         //print_r($grade_arr['level_name']);exit;
        
        //计算提升进度
        if ($show_progress == true){
            if (intval($grade_arr['level']) >= (count($member_grade) - 1)){//如果已达到顶级会员
                $grade_arr['downgrade'] = $grade_arr['level'] - 1;//下一级会员等级
                $grade_arr['downgrade_name'] = $member_grade[$grade_arr['downgrade']]['level_name'];
                $grade_arr['downgrade_exppoints'] = $member_grade[$grade_arr['downgrade']]['exppoints'];
                $grade_arr['upgrade'] = $grade_arr['level'];//上一级会员等级
                $grade_arr['upgrade_name'] = $member_grade[$grade_arr['upgrade']]['level_name'];
                $grade_arr['upgrade_exppoints'] = $member_grade[$grade_arr['upgrade']]['exppoints'];
                $grade_arr['less_exppoints'] = 0;
                $grade_arr['exppoints_rate'] = 100;
            } 
            else {
                $grade_arr['downgrade'] = $grade_arr['level'];//下一级会员等级
                $grade_arr['downgrade_name'] = $member_grade[$grade_arr['downgrade']]['level_name'];
                $grade_arr['downgrade_exppoints'] = $member_grade[$grade_arr['downgrade']]['exppoints'];
                $grade_arr['upgrade'] = $member_grade[$grade_arr['level']+1]['level'];//上一级会员等级
                $grade_arr['upgrade_name'] = $member_grade[$grade_arr['upgrade']]['level_name'];
                $grade_arr['upgrade_exppoints'] = $member_grade[$grade_arr['upgrade']]['exppoints'];
                $grade_arr['less_exppoints'] = $grade_arr['upgrade_exppoints'] - $exppoints;
                $grade_arr['exppoints_rate'] = round(($exppoints - $member_grade[$grade_arr['level']]['exppoints'])/($grade_arr['upgrade_exppoints'] - $member_grade[$grade_arr['level']]['exppoints'])*100,2);
            }
        }
        return $grade_arr;
    }
    
    
    
    
    
    
    
    /**
     * *****************************************************
     * add by liudongdong
     * *****************************************************
     */
    
    /**
     * 获取某会员上一级节点的会员ID
     * @param type $member_id
     * @return int
     */
    public function getParentNodeId($member_id)
    {
       $member=$this->getMemberInfo(array('member_id'=>$member_id));
       if(empty($member))
       {
          return 0; 
       }
      
       return $member['inviter_id'];
    }
    /**
     * 获取某会员的下一级会员
     * @param type $member_id
     * @return type
     */       
    public function getChildNodes($member_id)
    {
        $memberList=$this->getMemberList(array('inviter_id'=>$member_id));
        return $memberList;
    }
     public function getChildNodesCount($member_id)
    {
        $count=$this->getMemberCount(array('inviter_id'=>$member_id));
        return $count;
    }
    
    
    public function getParentNodeId2($member_id)
    {
       $member=$this->getMemberInfo(array('member_id'=>$member_id));
       if(empty($member))
       {
          return 0; 
       }
      
       return $member['node_id'];
    }
    
    
    public function  getChildNodes2($member_id)
    {
        $memberList=$this->getMemberList(array('node_id'=>$member_id));
        return $memberList;
    }
    
    public function getChildNodesCount2($member_id)
    {
        $count=$this->getMemberCount(array('node_id'=>$member_id));
        return $count;
    }
    /**
     * 获取注册某等级会员所对应的会员费
     * @param type $member_type
     * @return int
     */
    public function getConsumeAmountByMemberType($member_type)
    {
        switch ($member_type)
        {
            case '1':
                $result= COMMON_MEMBER;
                break;
            case '2':
                $result= GUEST_MEMBER;
                break;
            case '3':
                $result= VIP_MEMBER;
                break;
            case '4':
                $result= STORE_MEMBER;
                break;
            case '5':
                $result= STORE_MEMBER;
                break;
            default :
                $result= 0;
                break;
            
        }
        return $result;
    }

    
    /**
     * 计算一天的宝豆释放量
     * @param type $member_type
     * @return int
     */
    public function getBeanInDayByMemberFee($member_fee)
    {   
        $bean=$member_fee*10/20;
        return $bean;
    }
    /**
     * 获取会员等级名称
     * @param type $member_type
     * @return string
     */
    public function getMemberTypeName($member_type)
    {
        switch ($member_type)
        {
            case '1':
                $result= '普通会员';
                break;
            case '2':
                $result= '贵宾会员';
                break;
            case '3':
                $result= 'VIP会员';
                break;
            case '4':
                $result= '店长';
                break;
            case '5':
                $result= '报单中心';
                break;
            default :
                $result= '';
                break;
            
        }
        return $result;
    }
    /**
     * 根据节点人计算
     * 获取某会员的所有下线会员和此会员的总业绩
     * @param type $member_id
     */
    public function getDownLineMembersAndFee($member_id)
    {
       
        $member_fee_total=0;
        $childNodes=$this->getChildNodes2($member_id);
        foreach($childNodes as $childNode)
        {   
            $member_fee=$childNode['member_fee'];
            $member_fee=$member_fee+$member_fee*$childNode['repeat_count'];
            $member_fee_total+=$member_fee;
            self::$downline_member_fee=self::$downline_member_fee+$member_fee_total;
            self::$downline_members[]=$childNode['member_id'];
            $this->getDownLineMembersAndFee($childNode['member_id']);
        }
    }
    /**
     * 根据推荐人计算
     * 获取某会员的所有下线会员和此会员的总业绩
     * @param type $member_id
     */
    public function getDownLineMembersAndAchievement($member_id)
    {
       
        $member_fee_total=0;
        $childNodes=$this->getChildNodes($member_id);
        foreach($childNodes as $childNode)
        {   
            $member_fee=$childNode['member_fee'];
            $member_fee=$member_fee+$member_fee*$childNode['repeat_count'];
            $member_fee_total+=$member_fee;
            self::$downline_member_fee=self::$downline_member_fee+$member_fee_total;
            self::$downline_members[]=$childNode['member_id'];
            $this->getDownLineMembersAndAchievement($childNode['member_id']);
        }
    }
    
    /**
     * 获取某会员的所有上级会员和其对应的业绩
     * @param type $member_id
     */
    public function getUpLineMembersAndFee($member_id)
    {
        self::$upline_member_and_fee=[];
        
        $upline_member_id=$this->getParentNodeId2($member_id);
        if($upline_member_id)
        {
             $temp=[];
             $temp['member_id']=$upline_member_id;
             $this->getDownLineMembersAndFee($upline_member_id);
             $temp['fee']= self::$downline_member_fee;
             self::$upline_member_and_fee[]=$temp;
             $this->getUpLineMembersAndFee($upline_member_id);
        }
       
    }
    
    /**
     * 
     * @param type $member_fee 会员费（业绩）
     * @param type $percent_array
     * @return int
     */
    public function getPercent($member_fee,$percent_array=array())
    {
         $percent=0;
         if($member_fee>=20000&$member_fee<50000)
         {
            $percent= PERCENT1;
         }
         else if($member_fee>=50000&$member_fee<100000)
         {
             $percent= PERCENT2;
         }
         else if($member_fee>=100000)
         {
             $percent= PERCENT3;
         }
         else
         {
             $percent= 0;
         }
         if($percent==0)
         {
             return $percent;
         }
        
         foreach($percent_array as $v)
         {
             $percent=$percent-$v;
         }
         
         return $percent;
         
    }
    /**
     * 
     * @param type $member_fee 会员费（业绩）
     * @param type $range_array
     * @return int
     */
    public function getRange($member_fee,$range_array=array())
    {
         $range=0;
         if($member_fee>=20000&$member_fee<50000)
         {
            $range= 1;
         }
         else if($member_fee>=50000&$member_fee<100000)
         {
             $range= 2;
         }
          else if($member_fee>=100000)
         {
             $range= 3;
         }
         else
         {
             $range= 0;
         }
         if($range==0)
         {
             return $range;
         }
         
        for($range;$range>=1;$range--)
        {
            if(!in_array($range, $range_array))
            {
                return $range;
            }
        }
         
         return $range;
         
         
         
    }

    /**
     * 获取某业绩区间所对应的奖励百分比
     * @param type $range
     * @return int
     */
    public function getRangeOfPercent($range)
    {
        $percent=0;
        switch ($range)
        {
            case 1:
                $percent=PERCENT1;
                break;
            case 2:
                $percent=PERCENT2;
                break;
            case 3:
                $percent=PERCENT3;
                break;
            default:
                $percent=0;
                break;
        }
        return $percent;
         
    }
    
    /**
     * 奖励专用（含扣费，扣税，平台管理费，复投费）
     * @param type $member_id 被奖励人的会员ID
     * @param type $amount 奖励金额
     * @param type $reward_type 奖励类型 share_reward（分享奖） dynamic_reward（动态奖）welfare_reward（福利奖）submit_form(报单补助)
     * @param type $register_member_id 新注册会员的ID
     * @param type $register_member_name 新注册会员的名称
     * @param type $register_member_type 新注册会员的等级
     */
    public function writeLog($member_id,$amount,$reward_type,$register_member_id,$register_member_name,$register_member_type)
    {
         $data = array();
        
         $member=$this->getMemberInfo(array('member_id'=>$member_id));
         $data['member_id'] = $member_id;
         $data['member_name'] =empty($member)?'': $member['member_name'];
         
         $tax=$amount*TAX;//扣税
         $manage_fee=$amount*MANAGE_FEE;//平台管理费
         $repeat_fee=$amount*REPEAT_FEE;//复投费
         
         $data['amount'] = $amount-$tax-$manage_fee-$repeat_fee;//奖励金额
         
         $data['tax'] = $tax;
         $data['manage_fee'] = $manage_fee;
         $data['repeat_fee'] = $repeat_fee;
         
         $data['repeat_wallet'] = $repeat_fee;//复投金额
         $data['register_member_id'] = $register_member_id;
         $data['register_member_name'] = $register_member_name;
         $data['register_member_type'] =$this->getMemberTypeName($register_member_type) ;
        
         $model_pd = Model('predeposit');
         $model_pd->changePd($reward_type,$data);
        
    }
    
    
    
    
    
    
    
    
    /**
     * 复投处理
     * 有新会员注册的时候触发检测所有会员复投钱包的余额是否大于等于其会员费，然后此人的账号再次被“注册”，从而再次激活各种奖励
     * @param type $member_id  被奖励人的会员ID
     */
    public function repeatRegister()
    {
        $condition=array();
        $condition['member_id'] = array('gt',0);
        $member_list=$this->getMemberList($condition);
        foreach($member_list as $member)
        {
             $member_fee=$member['member_fee'];
             if($member['repeat_wallet']>=$member_fee)
            {
                 $data=array();
                 $data['repeat_count']=array('exp','repeat_count+1');
                 $data['repeat_wallet']=array('exp','repeat_wallet-'.$member_fee);
                 $this->editMember(array('member_id'=>$member['member_id']), $data);

                 //记录消费日志
                QueueClient::push('addConsume', array('member_id'=>$member['member_id'],'member_name'=>$member['member_name'],
                'consume_amount'=>$member_fee,'consume_time'=>TIMESTAMP,'consume_remark'=>'复投会员，消费'.$member_fee));

                if(!empty($member['inviter_id']))
                {
                     $this->shareReward($member['inviter_id'],$member_fee,$member['member_id'],$member['member_name'],$member['member_type']);
                     $this->dynamicReward($member['inviter_id'], $member_fee, $member['member_id'],$member['member_name'],$member['member_type']);
                    
                }
                if(!empty($member['node_id']))
                {
                     $this->welfareReward($member['node_id'], $member_fee, $member['member_id'],$member['member_name'],$member['member_type']);
                }

            }
            
        }
        
        
        
    }
    
   
    
    
    /**
     * 分享奖处理
     * @param type $inviter_id 推荐人的会员ID
     * @param type $member_fee 会员费
     * @param type $register_member_id 新注册的会员ID
     * @param type $register_member_name 新注册的会员名称
     * @param type $register_member_type 新注册的会员等级
     */
    public function shareReward($inviter_id,$member_fee,$register_member_id,$register_member_name,$register_member_type)
    {
        //推荐人的预存款账户增加会员费的20%
        $amount=$member_fee*SHARE_PERCENT;//分享奖励金额
        //增加推荐人预存款 
        $this->writeLog($inviter_id, $amount, 'share_reward', $register_member_id, $register_member_name, $register_member_type);
    }
    /**
     * 动态奖处理
     * @param type $inviter_id
     * @param type $member_fee
     * @param type $register_member_id
     * @param type $register_member_name
     * @param type $register_member_type
     */
    public function dynamicReward($inviter_id,$member_fee,$register_member_id, $register_member_name, $register_member_type)
    {
        $member=$this->getMemberInfo(array('member_id'=>$inviter_id));
        $parentNodeId=$member['invite_one'];//推荐人的父节点
        $grandfatherNodeId=$member['invite_two'];//推荐人的祖父节点

        //推荐人的父节点下的孩子数量
        $parentNode_childNodesCount=$this->getChildNodesCount($parentNodeId);
        //推荐人的祖父节点下的孩子数量
        $grandfatherNode_childNodesCount=$this->getChildNodesCount($grandfatherNodeId);

        /**
         * 推荐人父节点拿取动态奖处理 begin
         */

         //不管父级节点推荐了几个会员，一代会员的分享奖只会被拿取10%
         $amount = $member_fee*SHARE_PERCENT*DYNAMIC_PERCENT1;//奖励金额
        
         if($parentNodeId>0&&$amount>0)
         {
            $this->writeLog($parentNodeId, $amount, 'dynamic_reward', $register_member_id, $register_member_name, $register_member_type);
         }
        /**
         * 推荐人父节点拿取动态奖处理 end
         */

        /**
         * 推荐人祖父节点拿取动态奖处理 begin
         */

         //祖父节点是否能拿取推荐人的分享奖抽成(30%)，取决于祖父节点下的孩子数量是否>=2
         if($grandfatherNode_childNodesCount>=2)
         {
            $amount = $member_fee*SHARE_PERCENT*DYNAMIC_PERCENT2;//奖励金额
            if($grandfatherNodeId>0&&$amount>0)
            {
               $this->writeLog($grandfatherNodeId, $amount, 'dynamic_reward',$register_member_id, $register_member_name, $register_member_type);
            }
            
         }

         /**
         * 推荐人祖父节点拿取动态奖处理 end
         */
         
         
         /**
          * 推荐人作为领导，他的孩子节点拿取动态奖的处理 begin
          */
             $count=0;
             $member_id_array=[];
             $inviter_childNodes=$this->getChildNodes($inviter_id);

             foreach($inviter_childNodes as $inviter_childNode)
             {
                 $inviter_childNode_childNodesCount=$this->getChildNodesCount($inviter_childNode['member_id']);
                 if($inviter_childNode_childNodesCount>=3)
                 {
                     $count=$count+1;
                     $member_id_array[]=$inviter_childNode['member_id'];
                 }

             }
             if($count>=1)
             {
                $amount = ($member_fee*SHARE_PERCENT*DYNAMIC_PERCENT3)/$count;//奖励金额
             }
             else
             {
                 $amount=0;
             }
            
             if($amount>0)
             {
                 foreach($member_id_array as $v)
                 {
                    $member_id = $v;
                    $this->writeLog($member_id, $amount, 'dynamic_reward',$register_member_id, $register_member_name, $register_member_type);
                 }
             }

             /**
             * 推荐人作为领导，他的孩子节点拿取动态奖的处理 end
             */
            

        
    }
    /**
     * 福利奖处理
     * 新会员注册时其推荐人的业绩增加，触发检测其推荐人的总业绩，推荐人上级节点的总业绩
     * @param type $inviter_id
     * @param type $member_fee
     * @param type $register_member_id
     * @param type $register_member_name
     * @param type $register_member_type
     */
    public function welfareReward($inviter_id,$member_fee,$register_member_id, $register_member_name, $register_member_type)
    {
         /**
          * 推荐人的福利奖处理 begin
          */
         $percent_array=[];
         $this->getDownLineMembersAndFee($inviter_id);
         $downline_member_array= self::$downline_members;//推荐人的所有下线会员
         $downline_member_fee_total=self::$downline_member_fee;//推荐人的所有业绩之和

         $percent=$this->getPercent($downline_member_fee_total);
         if($percent>0)
         {
             $percent_array[]=$percent;
             $amount = $member_fee*$percent;//奖励金额
             $this->writeLog($inviter_id, $amount, 'welfare_reward', $register_member_id, $register_member_name, $register_member_type);
         }

         /**
          * 推荐人的福利奖处理 end
          */

         
         /**
          * 推荐人上级所有节点处理 begin
          */

         $this->getUpLineMembersAndFee($inviter_id);
         $upline_member_and_fee_list=self::$upline_member_and_fee;

         foreach($upline_member_and_fee_list as $upline_member_and_fee)
         {
             $percent=$this->getPercent($upline_member_and_fee['fee'],$percent_array);

             if($percent>0)
             {
                $percent_array[]=$percent;
                $amount = $member_fee*$percent;//奖励金额
                $this->writeLog($upline_member_and_fee['member_id'], $amount, 'welfare_reward', $register_member_id, $register_member_name, $register_member_type);
             }
         }

         /**
          * 推荐人上级所有节点处理 end
          */

    }
}
